#!/bin/bash
mkdir -p /opt/kubernetes/conf
mkdir -p /opt/kubernetes/ssl
mkdir -p /opt/kubernetes/log
mkdir -p /opt/kubernetes/etcd
mkdir -p /opt/kubernetes/kubelet
mkdir -p /opt/kubernetes/kube-proxy

cd /opt/kubernetes/ssl

cat > ca-csr.json <<"EOF"
{
  "CN": "kubernetes",
  "key": {
      "algo": "rsa",
      "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "Beijing",
      "L": "Beijing",
      "O": "kubesyd",
      "OU": "CN"
    }
  ],
  "ca": {
          "expiry": "87600h"
  }
}
EOF

cfssl gencert -initca ca-csr.json | cfssljson -bare ca

cat > ca-config.json <<"EOF"
{
  "signing": {
      "default": {
          "expiry": "87600h"
        },
      "profiles": {
          "kubernetes": {
              "usages": [
                  "signing",
                  "key encipherment",
                  "server auth",
                  "client auth"
              ],
              "expiry": "87600h"
          }
      }
  }
}
EOF

cat > etcd-csr.json <<"EOF"
{
  "CN": "etcd",
  "hosts": [
    "127.0.0.1",
    "$LOCAL_IP"
  ],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [{
    "C": "CN",
    "ST": "Beijing",
    "L": "Beijing",
    "O": "kubesyd",
    "OU": "CN"
  }]
}
EOF

cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes etcd-csr.json | cfssljson  -bare etcd

cd /opt/kubernetes/conf

cat >  etcd.conf <<"EOF"
name: 'etcd'
data-dir: '/opt/kubernetes/etcd'
listen-client-urls: 'https://192.168.5.87:2379,http://127.0.0.1:2379'
EOF

cd /etc/systemd/system

cat > etcd.service <<"EOF"
[Unit]
Description=Etcd Server
After=network.target
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
EnvironmentFile=-/opt/kubernetes/conf/etcd.conf
WorkingDirectory=/opt/kubernetes/etcd/
ExecStart=/usr/local/bin/etcd 
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload

systemctl enable etcd

systemctl start etcd

systemctl status etcd


